<template>
  <div class="page-wrapper">
    <div class="goods-main-info">
      <div class="goods-imgs">
        <el-carousel class="banners" :interval="5000">
          <el-carousel-item v-for="(item,index) in skuObj.gallery" :key="index">
           <img :src="item" class="slide-image" mode="aspectFit" />
          </el-carousel-item>
        </el-carousel>

      </div>
      <div class="goods-title">
        <div class="goods-price">
          <div class="price">
            <div class="main-price">
              <div class="icon-rmb">￥</div>{{skuObj.productPromotePrice}}
            </div>
            <div class="sub-price">￥{{skuObj.productPrice}}</div>
          </div>
          <div class="store">库存{{skuObj.productStock}}件</div>
        </div>
        <div class="share-title">
          <div class="goods-name">{{detailObj.productName}}</div>
          <button class="share-btn" open-type="share">
            <img class="icon-share" src="../../assets/icon-share.png" mode="aspectFit"/>
            <div>分享好礼</div>
          </button>
        </div>
      </div>
    </div>
    <div class="sku-info" @click="openSku" v-if="detailObj.specifications">
      <div class="sku-title">规格</div>
      <div class="select">{{skuName ? skuName : '请选择' }}<img class="icon-go" src="../../assets/icon-go.png" mode="aspectFit"/></div>
    </div>
    <div class="sku-info">
      <div class="sku-title">快递</div>
      <div class="select">￥{{detailObj.freightPrice}}</div>
    </div>

    <div class="detail-info main-detail-content">
      <detailInfo  :detailInfo.sync="detailDes"></detailInfo>
    </div>
    <div class="fix-footer">
      <div class="service" @click="callService">
        <div class="service-img">
          <img class="icon-service" src="../../assets/icon-service.png"/>
        </div>
        <div class="service-font">客服</div>
      </div>
      <div class="service collect-btn" @click="addCollect">
        <div class="service-img">
          <span class="icon-service"  :class="!scimg ? 'collected' : 'unCollect'"/>
        </div>
        <div class="service-font">{{scFont}}</div>
      </div>

      <div class="handle-btns">
        <div class="btn" @click="addCar">
          加入购物车
        </div>
        <div class="btn shop-btn" @click="subBuy">
          立即购买
        </div>
      </div>
    </div>

     <!-- 复制弹窗 -->
    <div :class="['copy-modal', isCopyModal ? 'copy-modal-show' : '']" catchtouchmove="ture">
      <div class="copy-modal-bg" catchtouchmove="true" @click="toggleStatus('isCopyModal', false)"></div>
      <div class="copy-modal-content" catchtap>
        <div class="close-btn" @click="toggleStatus('isCopyModal', false)">
          <img class="close" src="../../assets/close.png" mode="aspectFill"/>
        </div>
        <div class="info-header" v-if="skuObj.gallery && skuObj.gallery.length">
          <img class="goods-img" :src="skuObj.gallery[0]" mode="aspectFit"/>
          <div class="goods-info">
            <div class="info-title">{{detailObj.productName}}</div>
            <div class="info-price">￥<div class="rmb">{{skuObj.productPromotePrice}}</div></div>
          </div>
        </div>
        <div class="skus-info" v-if="detailObj.specifications">
          <div class="skus-item">
            <div class="sku-items">
                <div :class="['sku-label', item == selVal ? 'active': '']" v-for="(item,index) in detailObj.specifications" :key="index">
                  <div class="it" @click="selectPropId(item)">{{item}}</div>
                </div>
            </div>
          </div>
        </div>
        <div class="buy-num">
          <div>购买数量</div>
          <div class="num-btns">
            <div class="subtract-btn" @click="subtract()">-</div>
            <div class="input-btn"><input class="input" :value="num" type="number" @input="input()" /></div>
            <div class="add-btn" @click="add()">+</div>
          </div>
        </div>
        <div class="handle-btn">
          <button class="sub-btn" @click="subCopyCar()">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { API } from '../../config'
import detailInfo from './components/detailInfo'
export default {
  name:'detail',
  data() {
    return {
      indicatorDots: true,
      isCopyModal: false,
      tab: 0,
      detailObj: {},
      skuObj: {},
      num: 1,
      skuName: '',
      selArr: [],
      detailDes: {
        productDescription: '',
        buyInstructions: ''
      },
      btntype: 0,
      collectId:'',//收藏id
      //定义样式字
      scFont:'',
      scimg:false,
      scFontsize:'',
      selVal:''
    }
  },
  components: {
    detailInfo: detailInfo, // 引入组件
  },
  methods : {
    // 打开弹窗
    openSku() {
      this.btntype = 0
      this.isCopyModal = true
    },
    // 切换tab
    toggleTab(e) {
      this.tab = parseInt(e.detail.value)
    },

    subCopyCar() {
      let vm = this
      if (vm.judgeSku()) {
        vm.$message('请选择商品规格')
      } else {
        if (vm.btntype === 0) {
          // 选择规格
        } else if (vm.btntype === 1) {
          vm.subBuy()
          // 立即购买
        } else if (vm.btntype === 2) {
          // 加入购物车
          vm.addCar()
        }
        vm.isCopyModal = false
      }
    },
    /**
     * 操作弹窗
     */
    toggleStatus(type, isTrue) {
      const bool = isTrue === 'true'
      switch (type) {
        case 'isCopyModal':
          this.isCopyModal = bool
          break
        case 'isConfirm':
          this.isConfirm = bool
          break
        default:
          break
      }
    },
    /**
     * 数量增加
     */
    add() {
      let vm = this
      vm.num ++
    },
    /**
     * 数量减少
     */
    subtract() {
      let vm = this
      if(vm.num > 0){
        vm.num --
      }else{
        vm.num = 0
      }
      
    },
    /**
     * 数量减少
     */
    input(e) {
      const n = parseInt(e.target.detail)
      this.numObj.setNum(n)
      this.change()
    },

    // 购买
    subBuy() {
      if (this.judgeSku()) {
        this.btntype = 1
        this.isCopyModal = true
      }else{
        this.$router.push({
          path: `/order/order?productSkuId=${this.skuObj.productSkuId}&num=${this.num}`
        })
      }
      
    },
    // 加入购物车
    addCar() {
      let vm = this
      if (vm.judgeSku()) {
        vm.btntype = 2
        vm.isCopyModal = true
      }else{
        let accesstoken = vm.getLocalStorage('accesstoken')
        vm.$axios.post(API + '/shoppingcart/add',{productSkuId: this.skuObj.productSkuId, productNumber: this.num},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((response) => {
          if(response.data.code == '200') {
            vm.$message('加入购物车成功')
          }else {
            vm.$message('加入购物车失败');
          }
          vm.skuName = ''
          vm.selVal = ''
        })
      }
    },
    // 添加收藏  要传的参数  productId商品id  productSkuId商品sku的id
    addCollect() {
      //这个this给获取收藏状态的接口，取收藏id
      let vm = this
      let accesstoken = vm.getLocalStorage('accesstoken')
      vm.$axios.get(API + '/user/collect/productStatus?productId=' + vm.$route.query.id,{
          headers: {'accesstoken': accesstoken} //设置header信息
        }).then((response) => {
        vm.collectId = response.data.data
        //如果值为null或者-1，表示未收藏，执行收藏接口
        if(vm.collectId=='-1'||vm.collectId===null) {
          let vm = this
          vm.$axios.post(API + '/user/collect/add',{productId: vm.$route.query.id,productSkuId:''},{
          headers: {'accesstoken': accesstoken} //设置header信息
        }).then((response) => {
            if(response.data.code===200){
              vm.collectId = response.data.data;
              vm.scimg = false
              vm.scFont = "取消收藏"
              vm.scFontsize = "26"
              // console.log("添加收藏后的收藏id(vmSc)："+vmSc.data.collectId);
              vm.$message('收藏成功')
            }else {
              vm.$message('收藏失败')
            }
          })
        //如果有值且不为空或-1，表示商品已被收藏，执行取消收藏接口
        }else if(vm.collectId!=='-1'||vm.collectId!==''){
          let vm = this
          vm.$axios.get(API + '/user/collect/del/'+ vm.collectId,{
          headers: {'accesstoken': accesstoken} //设置header信息
        }).then((response) => {
            if(response.data.code===200){
              vm.collectId = response.data.data;
              vm.scimg = true
              vm.scFont = "收藏"
              // console.log("添加收藏后的收藏id(vmSc)："+vmSc.data.collectId);
              vm.$message('取消收藏')
            }else {
              vm.$message('取消收藏失败')
            }
          })
        }
      })
    },
    // 选择sku
    selectPropId(item) {
      let vm = this
      vm.selVal = vm.selVal === item ? '' : item
      vm.getSku()
    },

    //获取商品是否收藏
    isCollection() {
      let vm = this
      let accesstoken = vm.getLocalStorage('accesstoken')
      vm.$axios.get(API + '/user/collect/productStatus?productId=' + vm.$route.query.id,{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((response) => {
        let vm = this;
        if(response.data.data=='-1'||response.data.data===null) {
          vm.scimg = true
          vm.scFont = "收藏"
        }
        //已收藏状态
        else if(response.data.data!=='-1'||response.data.data!==''){
          vm.scimg = false
          vm.scFont = "取消收藏"
          vm.scFontsize = "26"
        }
      })
    },
    judgeSku() {
      return this.detailObj.specifications.length && !this.skuName && !this.selVal
    },
    /**
     * 数量变化
     */
    change() {
      this.num = this.numObj.getNum()
      // 数量变化处理逻辑
    },
    /**
     * 获取商品详情
     *  */
    getDetail() {
      let vm = this
      let accesstoken = vm.getLocalStorage('accesstoken')
      vm.$axios.get(API + '/product/detail?productId='+vm.$route.query.id,{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((response) => {
        if(response.data.code=='200'){
          vm.detailObj = response.data.data
          const { productPrice, productPromotePrice, productStock, gallery, productSkuId, productId } = vm.detailObj
          vm.skuObj = { productPrice, productPromotePrice, productStock, gallery, productSkuId, productId }
          vm.numObj = vm.skuObj.productStock
          vm.detailDes = {
            productDescription: vm.detailObj.productDescription,
            buyInstructions: vm.detailObj.buyInstructions
          }
          vm.isCollection();
        }
      })

    },
    /**
     * 获取商品sku
     *  */
    getSku(params) {
      let vm = this
      this.detailObj.specifications.filter(item => {
          vm.skuName = item
      })
      if (vm.skuName) {
        let productId = vm.detailObj.productId
        let propValueIds = vm.skuName
        vm.$axios.post(API + '/product/skudetail',{productId:productId, propValueIds:propValueIds}).then((response) => {
          if(response.data.code=='200'){
            vm.numObj = vm.skuObj.productStock
            vm.num = 1
          }
        })
      }
    },
    // 转发好友
    onShareAppMessage() {
      return {
        title: this.detailObj.productName,
        path: '/goods/detail?id=' + this.detailObj.productId,
        imageUrl: this.detailObj.picUrl
      }
    },
    // 拨打客服电话
    callService(){
      window.location.href = "tel://18994140018";
    }
  },
  mounted() {
    let vm = this
    vm.getDetail();
  }
}
</script>

<style lang='less' scoped>
@import '../../css/goods/collectDetail.less';

</style>